<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '设备绑定',
    enablePullDownRefresh: true,
  },
}
</route>

<script setup lang="ts">
import { computed, ref } from 'vue'

// 搜索关键词
const searchKeyword = ref('')

// 当前选中的楼层id
const selectedFloorId = ref<number | null>(null)

// 建筑数据结构
const buildingData = ref([
  {
    id: 1,
    name: 'A区',
    expanded: true,
    children: [{
      id: 11,
      name: '1号楼',
      expanded: true,
      children: [{
        id: 111,
        name: '1层',
        rooms: [
          { id: 1111, name: '户号:301-A', bound: false },
          { id: 1112, name: '户号:301-B', bound: false },
          { id: 1113, name: '户号:302', bound: true },
        ],
      }, {
        id: 112,
        name: '2层',
        rooms: [
          { id: 1121, name: '户号:302', bound: false },
          { id: 1122, name: '户号:303', bound: false },
          { id: 1123, name: '户号:304', bound: true },
        ],
      }, {
        id: 113,
        name: '3层',
        rooms: [
          { id: 1131, name: '户号:305', bound: false },
          { id: 1132, name: '户号:306-A', bound: false },
          { id: 1133, name: '户号:306-B', bound: true },
        ],
      }, {
        id: 114,
        name: '4层',
        rooms: [
          { id: 1141, name: '户号:401', bound: false },
          { id: 1142, name: '户号:402', bound: false },
        ],
      }, {
        id: 115,
        name: '5层',
        rooms: [
          { id: 1151, name: '户号:501', bound: false },
          { id: 1152, name: '户号:502', bound: true },
        ],
      }],
    }, {
      id: 12,
      name: '2号楼',
      expanded: false,
      children: [{
        id: 121,
        name: '1层',
        rooms: [
          { id: 1211, name: '户号:601', bound: false },
          { id: 1212, name: '户号:602', bound: false },
        ],
      }, {
        id: 122,
        name: '2层',
        rooms: [
          { id: 1221, name: '户号:701', bound: false },
          { id: 1222, name: '户号:702', bound: true },
        ],
      }],
    }],
  },
  {
    id: 2,
    name: 'B区',
    expanded: false,
    children: [{
      id: 21,
      name: '1号楼',
      expanded: false,
      children: [{
        id: 211,
        name: '1层',
        rooms: [
          { id: 2111, name: '户号:801', bound: false },
          { id: 2112, name: '户号:802', bound: false },
        ],
      }],
    }],
  },
])

// 展开状态管理
const expandedNodes = ref<Set<number>>(new Set())

// 切换节点展开状态
function toggleExpand(nodeId: number) {
  if (expandedNodes.value.has(nodeId)) {
    expandedNodes.value.delete(nodeId)
  }
  else {
    expandedNodes.value.add(nodeId)
  }
}

// 展开/收起楼栋
function toggleBuilding(building: any) {
  building.expanded = !building.expanded
}

// 展开/收起楼号
function toggleFloor(floor: any) {
  floor.expanded = !floor.expanded
}

// 选择楼层
function selectFloor(floorId: number) {
  selectedFloorId.value = floorId
}

// 获取当前选中楼层的房间列表
const currentRooms = computed(() => {
  if (!selectedFloorId.value)
    return []

  for (const building of buildingData.value) {
    for (const floor of building.children) {
      for (const room of floor.children) {
        if (room.id === selectedFloorId.value) {
          return room.rooms || []
        }
      }
    }
  }
  return []
})

// 根据搜索关键词过滤房间
const filteredRooms = computed(() => {
  if (!searchKeyword.value)
    return currentRooms.value
  return currentRooms.value.filter(room =>
    room.name.toLowerCase().includes(searchKeyword.value.toLowerCase()),
  )
})

// 链接设备
function linkDevice(room: any) {
  if (room.bound) {
    uni.showToast({
      title: '设备已绑定',
      icon: 'none',
    })
    return
  }

  uni.showModal({
    title: '确认绑定',
    content: `确定要绑定${room.name}吗？`,
    success: (res) => {
      if (res.confirm) {
        // 模拟绑定操作
        room.bound = true
        uni.showToast({
          title: '绑定成功',
          icon: 'success',
        })
      }
    },
  })
}

// 扫码绑定指定房间
function scanCodeForRoom(room: any) {
  // #ifdef MP-WEIXIN
  uni.scanCode({
    success: (res) => {
      console.log('扫码结果:', res)
      uni.showModal({
        title: '确认绑定',
        content: `扫描到的内容：${res.result}\n\n确定要绑定到${room.name}吗？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            // 这里处理扫码绑定逻辑
            room.bound = true
            uni.showToast({
              title: `${room.name}扫码绑定成功`,
              icon: 'success',
            })
          }
        },
      })
    },
    fail: (err) => {
      console.error('扫码失败:', err)
      uni.showToast({
        title: '扫码失败',
        icon: 'none',
      })
    },
  })
  // #endif

  // #ifdef H5
  uni.showToast({
    title: 'H5暂不支持扫码',
    icon: 'none',
  })
  // #endif
}

// 初始化：默认展开第一个楼栋和第一个楼号
buildingData.value[0].expanded = true
buildingData.value[0].children[0].expanded = true
selectedFloorId.value = 111 // 默认选中第一个楼层
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <wd-search
        v-model="searchKeyword"
        placeholder="请输入房号"
        :show-action="false"
        hide-cancel
      />
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 左侧树形导航 -->
      <view class="left-nav">
        <view v-for="building in buildingData" :key="building.id" class="nav-item">
          <!-- 楼栋节点 -->
          <view
            class="nav-node building-node"
            :class="{ expanded: building.expanded }"
            @click="toggleBuilding(building)"
          >
            <view class="node-icon">
              <text class="icon-arrow" :class="{ rotate: building.expanded }">
                ▶
              </text>
            </view>
            <text class="node-text">
              {{ building.name }}
            </text>
          </view>

          <!-- 楼层节点 -->
          <view v-if="building.expanded" class="children-nodes">
            <view v-for="floor in building.children" :key="floor.id" class="nav-item">
              <!-- 楼号节点 -->
              <view
                class="nav-node floor-node"
                :class="{ expanded: floor.expanded }"
                @click="toggleFloor(floor)"
              >
                <view class="node-icon">
                  <text class="icon-arrow" :class="{ rotate: floor.expanded }">
                    ▶
                  </text>
                </view>
                <text class="node-text">
                  {{ floor.name }}
                </text>
              </view>

              <!-- 层级节点 -->
              <view v-if="floor.expanded" class="children-nodes">
                <view v-for="subFloor in floor.children" :key="subFloor.id" class="nav-item">
                  <view
                    class="nav-node sub-floor-node"
                    :class="{ active: selectedFloorId === subFloor.id }"
                    @click="selectFloor(subFloor.id)"
                  >
                    <view class="node-icon">
                      <text class="icon-dot">
                        ●
                      </text>
                    </view>
                    <text class="node-text">
                      {{ subFloor.name }}
                    </text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 右侧房间列表 -->
      <view class="right-content">
        <view v-if="filteredRooms.length === 0" class="empty-state">
          <text class="empty-text">
            {{ selectedFloorId ? '没有找到房间' : '请选择楼层' }}
          </text>
        </view>

        <view v-else class="room-list">
          <view v-for="room in filteredRooms" :key="room.id" class="room-item">
            <view class="room-info">
              <text class="room-number">
                {{ room.name }}
              </text>
              <view
                v-if="room.bound"
                class="status-badge bound"
              >
                已绑定
              </view>
            </view>

            <view class="room-actions">
              <wd-button
                type="primary"
                size="small"
                @click="scanCodeForRoom(room)"
              >
                扫码
              </wd-button>

              <wd-button
                v-if="!room.bound"
                :type="room.bound ? 'info' : 'warning'"
                size="small"
                :disabled="room.bound"
                @click="linkDevice(room)"
              >
                {{ room.bound ? '已绑定' : '链接' }}
              </wd-button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.search-bar {
  padding: 24rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.main-content {
  display: flex;
  height: calc(100vh - 120rpx);
  background-color: #f5f5f5;
}

.left-nav {
  width: 300rpx;
  background-color: #ffffff;
  border-right: 1rpx solid #f0f0f0;
  overflow-y: auto;
  padding: 20rpx 0;

  .nav-item {
    width: 100%;
  }

  .nav-node {
    display: flex;
    align-items: center;
    padding: 16rpx 24rpx;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f5f5f5;
    }

    &.active {
      background-color: #e6f3ff;
      color: #1890ff;

      .node-text {
        color: #1890ff;
        font-weight: 500;
      }
    }

    .node-icon {
      width: 32rpx;
      height: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16rpx;

      .icon-arrow {
        font-size: 20rpx;
        color: #666;
        transition: transform 0.2s;

        &.rotate {
          transform: rotate(90deg);
        }
      }

      .icon-dot {
        font-size: 12rpx;
        color: #999;
      }
    }

    .node-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.4;
    }
  }

  .building-node {
    font-weight: 500;

    .node-text {
      font-size: 30rpx;
    }
  }

  .floor-node {
    padding-left: 56rpx;

    .node-text {
      font-size: 28rpx;
    }
  }

  .sub-floor-node {
    padding-left: 88rpx;

    .node-text {
      font-size: 26rpx;
    }
  }

  .children-nodes {
    width: 100%;
  }
}

.right-content {
  flex: 1;
  background-color: #ffffff;
  padding: 20rpx;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  .empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200rpx;

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .room-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;

    .room-item {
      display: flex;
      flex-direction: column;
      background-color: #f9f9f9;
      padding: 24rpx;
      border-radius: 8rpx;
      border: 1rpx solid #e6e6e6;
      transition: all 0.2s;

      &:hover {
        background-color: #f0f0f0;
        border-color: #d9d9d9;
      }

      .room-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20rpx;

        .room-number {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .status-badge {
          padding: 4rpx 16rpx;
          border-radius: 16rpx;
          font-size: 22rpx;
          font-weight: 500;

          &.bound {
            background-color: #f6ffed;
            color: #52c41a;
            border: 1rpx solid #b7eb8f;
          }
        }
      }

      .room-actions {
        display: flex;
        gap: 16rpx;
        justify-content: flex-end;
        :deep(.wd-button) {
          padding: 0 56rpx;
        }
      }
    }
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8rpx;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4rpx;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
